import React, { useState } from 'react';
import { Card, Input, Button, QRCode, Space, message, Form, Typography } from 'antd';
import { QrcodeOutlined, ScanOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title, Text } = Typography;

const TestBinding = () => {
  const [form] = Form.useForm();
  const [qrValue, setQrValue] = useState('');
  const [loading, setLoading] = useState(false);

  const handleBind = async (values) => {
    setLoading(true);
    try {
      const response = await axios.post('http://localhost:3001/api/tests/bind', {
        boxId: values.boxId,
        batchNumber: values.batchNumber,
        firmwareVersion: values.firmwareVersion
      });
      
      if (response.data.success) {
        message.success('检测盒绑定成功！');
        setQrValue(JSON.stringify({
          boxId: values.boxId,
          batchNumber: values.batchNumber,
          firmwareVersion: values.firmwareVersion,
          timestamp: new Date().toISOString()
        }));
        form.resetFields();
      }
    } catch (error) {
      message.error('绑定失败：' + error.response?.data?.error || '未知错误');
    } finally {
      setLoading(false);
    }
  };

  const handleScan = () => {
    // 模拟扫码功能
    const mockData = {
      boxId: 'BOX-' + Date.now().toString().slice(-6),
      batchNumber: 'BATCH-' + new Date().toISOString().slice(0, 10).replace(/-/g, ''),
      firmwareVersion: 'v2.1.0'
    };
    
    form.setFieldsValue(mockData);
    message.success('扫码成功，已自动填充信息');
  };

  return (
    <div>
      <Title level={2}>检测盒绑定</Title>
      
      <Row gutter={[24, 24]}>
        <Col xs={24} lg={12}>
          <Card title="绑定新检测盒">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleBind}
            >
              <Form.Item
                label="检测盒ID"
                name="boxId"
                rules={[{ required: true, message: '请输入检测盒ID' }]}
              >
                <Input 
                  placeholder="请输入检测盒ID" 
                  prefix={<QrcodeOutlined />}
                />
              </Form.Item>
              
              <Form.Item
                label="批次号"
                name="batchNumber"
                rules={[{ required: true, message: '请输入批次号' }]}
              >
                <Input placeholder="请输入批次号" />
              </Form.Item>
              
              <Form.Item
                label="固件版本"
                name="firmwareVersion"
                rules={[{ required: true, message: '请输入固件版本' }]}
              >
                <Input placeholder="例如：v2.1.0" />
              </Form.Item>
              
              <Form.Item>
                <Space>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={loading}
                    icon={<QrcodeOutlined />}
                  >
                    绑定检测盒
                  </Button>
                  <Button 
                    icon={<ScanOutlined />}
                    onClick={handleScan}
                  >
                    模拟扫码
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>
        
        <Col xs={24} lg={12}>
          <Card title="二维码绑定信息">
            <div style={{ textAlign: 'center', padding: '20px' }}>
              {qrValue ? (
                <div>
                  <QRCode 
                    value={qrValue} 
                    size={200}
                    color="#1e3a8a"
                  />
                  <Text style={{ display: 'block', marginTop: 16, color: '#10b981' }}>
                    绑定成功！请保存此二维码
                  </Text>
                </div>
              ) : (
                <div style={{ 
                  width: 200, 
                  height: 200, 
                  margin: '0 auto',
                  border: '2px dashed #d9d9d9',
                  borderRadius: 8,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#999'
                }}>
                  绑定后生成二维码
                </div>
              )}
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default TestBinding;